﻿using System.Diagnostics;
using System.Text.Json.Serialization;
using System.Text.Encodings.Web;
using System.Text.Json;
using System.Text.Unicode;

namespace ZGDisassembler.Core;

/// <summary>
/// 配置文件
/// </summary>
public class Config
{
	/// <summary>
	/// 配置文件名称
	/// </summary>
	public const string ConfigFileName = "config.json";
	private static readonly string[] FileTypes = { "Binary", "HexString" };

	private static readonly JsonSerializerOptions jsonOption = new()
	{
		PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
		Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping,
		ReadCommentHandling = JsonCommentHandling.Skip,
		WriteIndented = true
	};

	#region 读取配置
	/// <summary>
	/// 读取配置
	/// </summary>
	/// <param name="configFile">打开文件所在路径，用于读取其配置文件</param>
	/// <param name="overwriteConfig">要重写的配置文件</param>
	/// <returns></returns>
	public void ReadConfig(string configFile)
	{
		if (!File.Exists(configFile))
		{
			Debug.WriteLine("配置文件不存在");
			return;
		}

		var fileStream = File.ReadAllText(configFile, Encoding.UTF8);
		var config = JsonSerializer.Deserialize<Config>(fileStream, jsonOption);
		if (config == null)
			return;

		var type = typeof(Config);
		var fields = type.GetProperties();
		foreach (var field in fields)
		{
			var value = field.GetValue(config);
			if (value == null)
				continue;

			field.SetValue(this, value);
		}
	}
	#endregion 读取配置

	#region 保存配置
	public void SaveConfig(string filePath)
	{
		var json = JsonSerializer.Serialize(this, jsonOption);
		File.WriteAllText(filePath, json, Encoding.Unicode);
	}
	#endregion 保存配置

	#region 属性
	/// <summary>
	/// 反编译平台
	/// </summary>
	public string? Platform { get; set; } = "6502";
	/// <summary>
	/// 是否允许标签
	/// </summary>
	public bool AbleLabel { get; set; } = false;
	/// <summary>
	/// 标签名称
	/// </summary>
	public string? LabelName { get; set; } = "label";
	/// <summary>
	/// 标签下标起始索引
	/// </summary>
	public uint? LabelStartIndex { get; set; } = 0;
	/// <summary>
	/// 是否使用替换标签
	/// </summary>
	public bool ReplaceLabel { get; set; } = false;
	/// <summary>
	/// 替换标签配置文件
	/// </summary>
	public string[] ReplaceLabelConfig { get; set; } = { "./labels/6502labels.ini" };
	/// <summary>
	/// 编译起始地址
	/// </summary>
	[JsonConverter(typeof(JsonHexConverter))]
	public uint? OrgAddress { get; set; } = 0x8000;
	/// <summary>
	/// 文件读取起始地址，仅对二进制文件类型有效
	/// </summary>
	[JsonConverter(typeof(JsonHexConverter))]
	public uint? BaseAddress { get; set; } = 0;
	/// <summary>
	/// 读取文件长度，仅对二进制文件类型有效
	/// </summary>
	[JsonConverter(typeof(JsonHexConverter))]
	public uint? ReadDataLength { get; set; }
	/// <summary>
	/// 文件类型, Binary 和 HexString
	/// </summary>
	public string? FileType
	{
		get => _fileType;
		set => _fileType = FileTypes.Contains(value) ? value : "Binary";
	}
	private string? _fileType = "Binary";
	#endregion 属性

}
